/**
 * 关于窗口程序逻辑
 */
const {remote, app, clipboard, getAppPath} = require('electron');
const {net} = remote;
const projectRoot = remote.getGlobal('projectPath');
const srcPath = remote.getGlobal('srcPath');
const path = require('path');
const exeFile = remote.app.getPath('exe');
const exePath = path.dirname(exeFile);

const tmpPath = `${exePath}/tmp`;

const core = require(`${srcPath}/mainlib/core`);
const Type = require(`${srcPath}/mainlib/type`);
const {animation_support} = require(`${srcPath}/mainlib/window-animation`);
const ipc = require(`${srcPath}/mainlib/ipc`);
const wndmgr = require(`${srcPath}/windows`);
const originfs = require('original-fs');
const fs = require('fs');
const request = require('request');
const AdmZip = require('adm-zip');
const cp = require('child_process');

var t = new Vue({
    el:'#root',
    
    data: {
        package: JSON.parse(fs.readFileSync(projectRoot + '\\package.json').toString()),
        updating: false,
        updatePercent: 0,
        isLatest: false,
    },
    
    mounted() {
        let self = this;
        remote.getCurrentWindow().on('show', function () {
            self.checkUpdate();
        });
        this.checkUpdate();
    },
    
    methods: {
        close(e) {
            e.preventDefault();
            let win = animation_support(remote.getCurrentWindow());
            win.hideWithAnimation();
        },
        
        getAppIcon() {
            return remote.app.getAppPath() + '\\' + this.package.icon;
        },
    
        openChangelogWindow() {
            wndmgr.open('changelog');
        },
        
        openUrl(url) {
            remote.shell.openExternal(url);
        },
        
        downloadFile(url, saveFile, params) {
            let xhr = new XMLHttpRequest();

            xhr.addEventListener('progress', e => {
                if (e.lengthComputable) {
                    params.progress && params.progress({
                        total: e.total,
                        received: e.loaded,
                        percent: Number(e.loaded / e.total*100).toFixed(2),
                    });
                }
            });

            xhr.responseType = 'blob';
            // xhr.overrideMimeType('text/plain; charset=x-user-defined');

            xhr.onload = function (e) {
                if(xhr.status == 200) {
                    let fileReader = new FileReader();
                    fileReader.onload = function() {
                        fs.writeFileSync(saveFile, Buffer.from(this.result));
                        params.end && params.end();
                    };
                    fileReader.readAsArrayBuffer(xhr.response);
                } else {
                    console.error(xhr.status, xhr.statusText);
                }
            };

            xhr.onerror = function (e) {
                console.error(xhr.status, xhr.statusText, e);
            };

            xhr.open('get', url);

            xhr.send();
        },
        
        checkUpdate() {
            let self = this;
            self.updating = 1;
            
            let checkUrl = 'http://vu.5jk.me/?sw=quick-start&v=' + this.package.version;
            
            fetch(checkUrl)
                .then( response => {
                    return response.json();
                })
                .then(json => {
                    let data = json.data;
                    
                    if(json.new && data.packages.length > 0) {
                        if(confirm(`发现新版本可用: ${data.latest}\n\n${data.detail}\n\n 是否进行更新?`)) {
                            this.updating = 2;
                            let tmpDownPath = tmpPath;
                            let tmpDownLoadFile = tmpDownPath + '/latest_resource.zip';
                            let tmpExtractDir = tmpDownPath + '/latest_resource';
                            let packageUrl = data.packages[0];
                            
                            if(data.full) {
                                remote.shell.openItem(packageUrl);
                            } else {
                                if(!core.isAsarMode()) {
                                    alert('当前程序模式不能在线更新');
                                    return;
                                }
                                
                                if(!fs.existsSync(tmpPath)) {
                                    fs.mkdirSync(tmpPath, {recursive :true});
                                }
                                
                                if(fs.existsSync(tmpExtractDir)) {
                                    core.deleteFolderRecursive(tmpExtractDir);
                                }

                                self.downloadFile(packageUrl, tmpDownPath + '/latest_resource.zip', {
                                    progress(data) {
                                        self.updatePercent = Math.round(data.percent);
                                        console.log(data.percent);
                                    },
                                    
                                    end() {
                                        self.updating = 3;
                                        let zip = new AdmZip(tmpDownLoadFile);
                                        zip.extractAllTo(tmpExtractDir);
                                        let tplPath, resourcePath;
                                        
                                        if(!core.isAsarMode()) {
                                            console.log('无法更新');
                                            return;
                                        }
                                        
                                        tplPath = exePath + '/resources/external-tools/restart.tpl.cmd';
                                        resourcePath = exePath + '/resources';
                                        
                                        if(!fs.existsSync(tplPath)) {
                                            console.error('缺少restart.tpl.cmd', tplPath);
                                            return;
                                        }
                                        
                                        let cmdtpl = String(fs.readFileSync(tplPath));

                                        cmdtpl = cmdtpl
                                            .replace(/{exe}/g, exeFile)
                                            .replace(/{from}/g, tmpExtractDir)
                                            .replace(/{to}/g, resourcePath)
                                            .replace(/{tmp}/g, tmpPath)
                                            .replace(/{delay}/g, 6)
                                        ;
                                        
                                        let cmdFile = tmpPath + '/restart.cmd';
                                        let buf = Buffer.from(require("iconv-lite").encode(cmdtpl, 'gbk'));
                                        fs.writeFileSync(cmdFile, buf);
                                        let logFile = exePath + '/restart.log';
                                        let cmd = `cmd /c "${cmdFile}" > "${logFile}" 2>&1`;
                                        
                                        cp.exec(cmd, function (error, stdout, stderr) {
                                            if (error) {
                                                console.error(error.stack);
                                                console.log('Error code: '+error.code);
                                                console.log('Signal received: '+error.signal);
                                            }
                                        });
                                        
                                        setTimeout(() => {
                                            remote.app.exit()
                                        }, 2000);
                                    }
                                })
                            }
                        }
                    } else {
                        self.isLatest = true;
                    }
                })
                .finally(e => {
                    self.updating = 0;
                })
            ;
        }
    },
    
    computed: {
        btnText() {
            if(!this.updating) {
                return "检查更新";
            }
            
            switch (this.updating) {
                case 1:
                    return "正在检测更新..";
                case 2:
                    return `正在下载更新..${this.updatePercent}%`;
                case 3:
                    return `正在安装更新..`;
            }
            
            return "更新中..";
        }
    },
    
});
